<template>
  <div class="activities">
    <div class="page-header">
      <h1>学术活动管理</h1>
      <div class="header-actions">
        <el-input
            v-model="searchText"
            placeholder="搜索活动名称"
            style="width: 200px; margin-right: 16px;"
            :prefix-icon="Search"
            clearable
        />
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增活动
        </el-button>
      </div>
    </div>

    <!-- 活动日历视图 -->
    <el-card class="calendar-card">
      <template #header>
        <div class="card-header">
          <span>活动日历</span>
          <el-button-group>
            <el-button
                :type="viewMode === 'calendar' ? 'primary' : ''"
                @click="viewMode = 'calendar'"
            >
              日历视图
            </el-button>
            <el-button
                :type="viewMode === 'list' ? 'primary' : ''"
                @click="viewMode = 'list'"
            >
              列表视图
            </el-button>
          </el-button-group>
        </div>
      </template>

      <div v-if="viewMode === 'calendar'" class="calendar-view">
        <el-calendar v-model="calendarDate">
          <template #date-cell="{ data }">
            <div class="calendar-cell">
              <div class="date-number">{{ data.day.split('-')[2] }}</div>
              <div v-for="activity in getActivitiesForDate(data.day)" :key="activity.id" class="activity-item">
                <el-tag :type="getActivityType(activity.activityType)" size="small">
                  {{ activity.activityName }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>

      <div v-else class="list-view">
        <!-- 筛选栏 -->
        <div class="filter-bar">
          <el-select v-model="filterType" placeholder="活动类型" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="学术会议" value="学术会议" />
            <el-option label="教学研讨会" value="教学研讨会" />
            <el-option label="培训" value="培训" />
            <el-option label="考察交流" value="考察交流" />
            <el-option label="竞赛评审" value="竞赛评审" />
            <el-option label="学术讲座" value="学术讲座" />
          </el-select>

          <el-select v-model="filterRole" placeholder="参与角色" style="width: 140px; margin-left: 16px;">
            <el-option label="全部" value="" />
            <el-option label="组织者" value="组织者" />
            <el-option label="主持人" value="主持人" />
            <el-option label="报告人" value="报告人" />
            <el-option label="参会代表" value="参会代表" />
            <el-option label="评委" value="评委" />
          </el-select>

          <el-select v-model="filterOrganizerLevel" placeholder="主办单位级别" style="width: 160px; margin-left: 16px;">
            <el-option label="全部" value="" />
            <el-option label="校级" value="校级" />
            <el-option label="市厅级" value="市厅级" />
            <el-option label="省部级" value="省部级" />
            <el-option label="国家级" value="国家级" />
            <el-option label="国际级" value="国际级" />
          </el-select>

          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="margin-left: 16px;"
          />

          <el-button style="margin-left: 16px;" type="primary" :loading="loading" @click="fetchActivities">查询</el-button>
        </div>

        <!-- 活动列表 -->
        <el-table :data="filteredActivities" stripe v-loading="loading">
          <el-table-column prop="activityName" label="活动名称" min-width="200" />
          <el-table-column prop="activityType" label="活动类型" width="110">
            <template #default="{ row }">
              <el-tag :type="getActivityType(row.activityType)">
                {{ row.activityType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="organizer" label="主办方" width="160" />
          <el-table-column prop="organizerLevel" label="主办级别" width="110" />
          <el-table-column label="地点" min-width="180">
            <template #default="{ row }">
              {{ row.location }}
            </template>
          </el-table-column>
          <el-table-column prop="startDate" label="开始日期" width="120">
            <template #default="{ row }">{{ formatDate(row.startDate) }}</template>
          </el-table-column>
          <el-table-column prop="endDate" label="结束日期" width="120">
            <template #default="{ row }">{{ formatDate(row.endDate) }}</template>
          </el-table-column>
          <el-table-column prop="status" label="审核状态" width="100">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.status)">
                {{ statusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="participantRole" label="参与角色" width="100" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="viewActivity(row)">查看</el-button>
              <el-button type="text" @click="editActivity(row)">编辑</el-button>
              <el-button type="text" style="color: #f56c6c;" @click="deleteActivity(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 12px; text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :page-size="pageSize"
            :current-page="page"
            :total="total"
            @current-change="onPageChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="showAddDialog"
        :title="editingActivity ? '编辑学术活动' : '新增学术活动'"
        width="700px"
    >
      <el-form :model="activityForm" :rules="activityRules" ref="activityFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="activityForm.activityName" />
        </el-form-item>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="活动类型" prop="activityType">
              <el-select v-model="activityForm.activityType" style="width: 100%">
                <el-option label="学术会议" value="学术会议" />
                <el-option label="教学研讨会" value="教学研讨会" />
                <el-option label="培训" value="培训" />
                <el-option label="考察交流" value="考察交流" />
                <el-option label="竞赛评审" value="竞赛评审" />
                <el-option label="学术讲座" value="学术讲座" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与角色" prop="participantRole">
              <el-select v-model="activityForm.participantRole" style="width: 100%">
                <el-option label="组织者" value="组织者" />
                <el-option label="主持人" value="主持人" />
                <el-option label="报告人" value="报告人" />
                <el-option label="参会代表" value="参会代表" />
                <el-option label="评委" value="评委" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                  v-model="activityForm.startDate"
                  type="date"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disableStartDate"
                  @change="onStartDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                  v-model="activityForm.endDate"
                  type="date"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disableEndDate"
                  @change="onEndDateChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="主办方" prop="organizer">
              <el-input v-model="activityForm.organizer" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主办级别" prop="organizerLevel">
              <el-select v-model="activityForm.organizerLevel" style="width: 100%">
                <el-option label="校级" value="校级" />
                <el-option label="市厅级" value="市厅级" />
                <el-option label="省部级" value="省部级" />
                <el-option label="国家级" value="国家级" />
                <el-option label="国际级" value="国际级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" />
        </el-form-item>

        <el-form-item label="是否报告" prop="hasReport">
          <el-switch v-model="activityForm.hasReport" />
        </el-form-item>

        <el-form-item v-if="activityForm.hasReport" label="报告题目" prop="reportTitle">
          <el-input v-model="activityForm.reportTitle" />
        </el-form-item>

        <el-divider content-position="left">证明材料</el-divider>
          <el-upload
              class="upload-demo"
              :auto-upload="false"
          :on-change="onFileSelect"
              multiple
          accept=".pdf,.jpg,.jpeg,.png,.ppt,.pptx"
          >
          <el-button>选择文件</el-button>
            <template #tip>
            <div class="el-upload__tip">支持PDF/JPG/PNG/PPT，大小按服务器限制</div>
            </template>
          </el-upload>
        <div v-if="editingActivity" style="margin-top: 8px;">
          <el-tag v-for="att in attachments" :key="att.id" style="margin-right: 8px; margin-bottom: 8px;">
            {{ att.fileName }}（{{ att.fileType }}）
            <el-icon style="cursor:pointer;margin-left:6px;" @click="removeAttachment(att)">×</el-icon>
          </el-tag>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveActivity">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog v-model="showViewDialog" title="活动详情" width="680px">
      <div v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动名称">{{ currentDetail.activityName }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">{{ currentDetail.activityType }}</el-descriptions-item>
          <el-descriptions-item label="主办单位">{{ currentDetail.organizer }}</el-descriptions-item>
          <el-descriptions-item label="主办级别">{{ currentDetail.organizerLevel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地点">{{ currentDetail.location }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ formatDate(currentDetail.startDate) }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ formatDate(currentDetail.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="参与角色">{{ currentDetail.participantRole }}</el-descriptions-item>
          <el-descriptions-item label="是否报告">{{ currentDetail.hasReport ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item v-if="currentDetail.hasReport" label="报告题目">{{ currentDetail.reportTitle || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">{{ statusText(currentDetail.status) }}</el-descriptions-item>
          <el-descriptions-item label="审核意见">{{ currentDetail.reviewComment || '-' }}</el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="left">证明材料</el-divider>
        <el-table :data="attachments" size="small" stripe>
          <el-table-column prop="fileName" label="文件名" min-width="220" />
          <el-table-column prop="fileType" label="类型" width="120" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <a class="el-link el-link--primary" :href="row.filePath" target="_blank">下载</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button type="primary" @click="showViewDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Download } from '@element-plus/icons-vue'
import activitiesApi from '@/api/activities'

// 响应式数据
const searchText = ref('')
const filterType = ref('')
const filterRole = ref('')
const filterOrganizerLevel = ref('')
const dateRange = ref([])
const viewMode = ref('list')
const calendarDate = ref(new Date())
const showAddDialog = ref(false)
const editingActivity = ref(null)
const activityFormRef = ref()
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查看弹窗
const showViewDialog = ref(false)
const currentDetail = ref(null)

// 活动数据
const activities = ref([])

// 新增：上传/附件列表的本地状态
const selectedFiles = ref([])
const attachments = ref([])

// 表单数据（与后端 DTO 对齐）
const activityForm = ref({
  activityName: '',
  activityType: '',
  organizer: '',
  organizerLevel: '',
  location: '',
  startDate: '',
  endDate: '',
  participantRole: '',
  hasReport: false,
  reportTitle: ''
})

// 表单验证规则
const activityRules = {
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  organizer: [{ required: true, message: '请输入主办方', trigger: 'blur' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (_, value, cb) => {
        if (!activityForm.value.startDate || !value) return cb()
        if (new Date(value) < new Date(activityForm.value.startDate)) {
          cb(new Error('结束日期不能早于开始日期'))
        } else cb()
      },
      trigger: 'change'
    }
  ],
  participantRole: [{ required: true, message: '请选择参与角色', trigger: 'change' }]
}

// 计算属性
const filteredActivities = computed(() => {
  let filtered = activities.value
  if (searchText.value) filtered = filtered.filter(a => (a.activityName || '').includes(searchText.value))
  return filtered
})

// 状态文本与样式
function statusText(status) {
  if (!status) return '审核中'
  if (status === 'APPROVED' || status === '已通过') return '已通过'
  if (status === 'REJECTED' || status === '已驳回') return '已驳回'
  return '审核中'
}
function statusTagType(status) {
  const t = statusText(status)
  if (t === '已通过') return 'success'
  if (t === '已驳回') return 'danger'
  return 'info'
}

// 方法
function getActivityType(type) {
  const types = {
    '学术会议': 'primary',
    '教学研讨会': 'warning',
    '培训': 'info',
    '考察交流': 'success',
    '竞赛评审': 'danger',
    '学术讲座': 'primary'
  }
  return types[type] || 'info'
}

function formatDate(val) {
  if (!val) return ''
  try { return String(val).substring(0, 10) } catch { return '' }
}

function getActivitiesForDate(date) {
  return activities.value.filter(a => formatDate(a.startDate) === date)
}

function onStartDateChange() {
  const s = activityForm.value.startDate
  const e = activityForm.value.endDate
  if (s && e && new Date(e) < new Date(s)) {
    activityForm.value.endDate = s
    ElMessage.warning('结束日期不能早于开始日期，已自动调整')
  }
}
function onEndDateChange() {
  const s = activityForm.value.startDate
  const e = activityForm.value.endDate
  if (s && e && new Date(e) < new Date(s)) {
    activityFormRef.value?.validateField?.('endDate')
  }
}

function disableStartDate(date) {
  const e = activityForm.value.endDate
  if (!e) return false
  try { return date.getTime() > new Date(e).getTime() } catch { return false }
}
function disableEndDate(date) {
  const s = activityForm.value.startDate
  if (!s) return false
  try { return date.getTime() < new Date(s).getTime() } catch { return false }
}

function resetForm() {
  activityForm.value = {
    activityName: '',
    activityType: '',
    organizer: '',
    organizerLevel: '',
    location: '',
    startDate: '',
    endDate: '',
    participantRole: '',
    hasReport: false,
    reportTitle: ''
  }
  editingActivity.value = null
}

function handleAdd() {
  resetForm()
  showAddDialog.value = true
}

function editActivity(row) {
  editingActivity.value = row
  activityForm.value = {
    activityName: row.activityName,
    activityType: row.activityType,
    organizer: row.organizer,
    organizerLevel: row.organizerLevel,
    location: row.location,
    startDate: formatDate(row.startDate),
    endDate: formatDate(row.endDate),
    participantRole: row.participantRole,
    hasReport: !!row.hasReport,
    reportTitle: row.reportTitle || ''
  }
  showAddDialog.value = true
  // 加载附件
  loadAttachments(row.id)
}

async function fetchActivities() {
  try {
    loading.value = true
    const params = {
      page: page.value,
      size: pageSize.value,
      type: filterType.value || undefined,
      role: filterRole.value || undefined,
      organizerLevel: filterOrganizerLevel.value || undefined,
      startDate: dateRange.value?.[0] || undefined,
      endDate: dateRange.value?.[1] || undefined
    }
    const res = await activitiesApi.list(params)
    activities.value = res?.content || []
    total.value = res?.totalElements || 0
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

function onPageChange(p) {
  page.value = p
  fetchActivities()
}

async function saveActivity() {
  try {
    await activityFormRef.value.validate()
    if (editingActivity.value) {
      await activitiesApi.update(editingActivity.value.id, activityForm.value)
      // 上传已选择的文件
      if (selectedFiles.value.length) {
        for (const f of selectedFiles.value) {
          const fd = new FormData()
          fd.append('file', f.raw)
          // 简单根据文件名推断类型，或让用户二选一
          const type = guessFileType(f.name)
          fd.append('fileType', type)
          await activitiesApi.uploadAttachment(editingActivity.value.id, fd)
        }
        selectedFiles.value = []
      }
      ElMessage.success('更新成功')
    } else {
      const id = await activitiesApi.create(activityForm.value)
      // 新增后如果选择了文件，则顺便上传
      if (id && selectedFiles.value.length) {
        for (const f of selectedFiles.value) {
          const fd = new FormData()
          fd.append('file', f.raw)
          const type = guessFileType(f.name)
          fd.append('fileType', type)
          await activitiesApi.uploadAttachment(id, fd)
        }
        selectedFiles.value = []
      }
      ElMessage.success('新增成功')
    }
    showAddDialog.value = false
    fetchActivities()
  } catch (e) {}
}

async function deleteActivity(row) {
  try {
    await ElMessageBox.confirm(`确定要删除活动"${row.activityName}"吗？`, '确认删除', { type: 'warning' })
    await activitiesApi.delete(row.id)
    ElMessage.success('删除成功')
    fetchActivities()
  } catch {}
}

async function viewActivity(row) {
  try {
    const detail = await activitiesApi.getById(row.id)
    currentDetail.value = detail
    attachments.value = await activitiesApi.listAttachments(row.id)
    showViewDialog.value = true
  } catch (e) {}
}

function onFileSelect(file, fileList) {
  selectedFiles.value = fileList
}

async function loadAttachments(id) {
  try {
    attachments.value = await activitiesApi.listAttachments(id)
  } catch {}
}

async function removeAttachment(att) {
  try {
    await ElMessageBox.confirm(`删除附件“${att.fileName}”？`, '确认', { type: 'warning' })
    await activitiesApi.deleteAttachment(att.id)
    if (editingActivity.value) loadAttachments(editingActivity.value.id)
    if (currentDetail.value) attachments.value = await activitiesApi.listAttachments(currentDetail.value.id)
    ElMessage.success('已删除')
  } catch {}
}

function guessFileType(name) {
  const n = (name || '').toLowerCase()
  if (n.includes('通知')) return '会议通知'
  if (n.includes('邀请')) return '邀请函'
  if (n.endsWith('.ppt') || n.endsWith('.pptx')) return '报告PPT'
  return '参会证明'
}

const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const filters = {
    search: searchText.value,
    type: filterType.value,
    role: filterRole.value,
    organizerLevel: filterOrganizerLevel.value,
    startDate: dateRange.value?.[0],
    endDate: dateRange.value?.[1]
  }
  
  await exportUtil('activities', filters, '学术活动列表.xlsx')
}

onMounted(fetchActivities)
</script>

<style scoped>
.activities {
  max-width: 1400px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
}

.calendar-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-cell {
  min-height: 80px;
}

.date-number {
  font-weight: 500;
  margin-bottom: 4px;
}

.activity-item {
  margin-bottom: 2px;
}

.activity-item .el-tag {
  font-size: 10px;
  padding: 0 4px;
  line-height: 16px;
}

.filter-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style>